<template>
  <div class="vxe-container">
    <div>
      <el-row>
        <!-- :is-add-show="!!(limits.length >=1 && limits.filter(it => it.FName === '新增').length)"
          :is-edit-show="!!(limits.length >=1 && limits.filter(it => it.FName === '修改').length)"
          :is-del-show="!!(limits.length >=1 && limits.filter(it => it.FName === '删除').length)" -->
        <BHeaderButton
          :is-add-show="false"
          :is-edit-show="false"
          :is-del-show="false"
          :is-refresh-show="true"
          :is-send-sms-show="true"
          :is-u8-show="false"
          :lists="options"
          :is-back-show="true"
          :is-settings-show="lookSetShow"
          @onAdd="vxeAdd(-1)"
          @onSave="vxeSave"
          @onDelete="vxeDel"
          @onU8="vxeU8"
          @onGoBack="goBack"
          @onSendSms="vxeSendSms"
          @onRefresh="refresh"
        

          @selectSettings="selectSettings" />
      </el-row>

      <br>

      <!-- 参数配置 -->
      <el-dialog
        v-el-drag-dialog
        :visible.sync="configModal"
        :close-on-click-modal="false"
        width="85%"
        class="config-dialog">
        <head-table :config-list="configList" :key-value="key" @updateConfigData="getUpdateConfigData" />
      </el-dialog>

      <!-- SQL弹窗 -->
      <el-dialog v-el-drag-dialog :visible.sync="dialogSQLModal" :append-to-body="true" title="执行结果">
        <el-form v-loading="loadingFormSQL" ref="formSQL" :rules="rulesSQL" :model="formSQL" label-width="120px">
          <el-form-item label="SQL语句" prop="gzsql">
            <el-input v-model="formSQL.gzsql" :autosize="{ minRows: 14 }" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button :loading="loadingFormSQL" type="primary" @click="confirmSQL">
              确认
            </el-button>
            <el-button @click="dialogSQLModal = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- SendMsg弹窗 -->
      <el-dialog v-el-drag-dialog :visible.sync="dialogSendMsgModal" :append-to-body="true" width="50%" title="发送信息">
        <el-tree
          ref="selectTree"
          :props="defaultProps"
          :data="sendUsrList"
          node-key="id"
          show-checkbox
          @node-click="handleNodeClick" />

        <br>

        <!-- {{mulSendMsgSelect}} -->
        <el-form ref="formSendMsg" :rules="rulesSendMsg" :model="formSendMsg" label-width="40px">
          <el-form-item label="内容" prop="fcontent">
            <el-input v-model="formSendMsg.fcontent" :autosize="{ minRows: 5 }" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button :loading="loadingFormSendMsg" type="primary" @click="confirmSendMsg">
              确认
            </el-button>
            <el-button @click="dialogSendMsgModal = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!-- style=" border:1px solid red;width:100%" -->
    <div style="margin-top: -20px">
      <div style="border: 1px solid #ddd">
        <vxe-form
          ref="vxeForm"
          :data="formData"
          :rules="{
            fprodectno: [{
              required: true,
              message: '请输入项目号',
              trigger: 'blur'
            }],
            fzhibaoqi: [{
              required: true,
              message: '请选择质保期',
              trigger: 'change'
            }]
        }">
          <template v-for="item in dialogThead">
            <template v-if="item.frepfld==='fzhibaoqi'">
              <vxe-form-item
                :key="item.frepfld"
                :title="item.frepcap"
                :field="item.frepfld"
                :title-colon="true"
                title-align="right"
                title-width="80px">
                <template #default>
                  <vxe-select v-model="formData[item.frepfld]" clearable filterable style="width: 120px;" placeholder="请选择">
                    <vxe-option
                      v-for="item in fzbqList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </vxe-select>
                </template>
              </vxe-form-item>
            </template>
            <template v-else>
              <vxe-form-item
                :key="item.frepfld"
                :title="item.frepcap"
                :field="item.frepfld"
                :title-colon="true"
                title-align="right"
                title-width="80px">
                <template v-if="item.fisedit == 1" #default>
                  <vxe-input v-model="formData[item.frepfld]" placeholder="请输入" clearable disabled />
                </template>
                <template v-else #default>
                  <vxe-input v-model="formData[item.frepfld]" placeholder="请输入" clearable />
                </template>

              </vxe-form-item>
            </template>
          </template>

        </vxe-form>
      </div>
      <vxe-grid
        ref="xGrid"
        v-bind="gridOptions"
        :seq-config="{
          startIndex: (tablePage.currentPage - 1) * tablePage.pageSize,
        }"
        :footer-cell-class-name="footerCellClassName"
        @edit-closed="cellClosed"
        @edit-actived="editActivedEvent"
        @toolbar-button-click="toolbarButtonClickEvent">

        <template #toolbar_buttons />

        <template #fwaibi_default="{ row }">
          <span>{{ formatField(row.fwaibi) }}</span>
        </template>
        <template #fwaibi_edit="{ row, column }">
          <vxe-select v-model="row.fwaibi" transfer @change="selectChangeEvent({ row, column })">
            <vxe-option v-for="item in fwaibiList" :key="item.value" :value="item.value" :label="item.label"/>
          </vxe-select>
        </template>
        <!-- <template #pager>
          <vxe-pager
            :layouts="[
              'Sizes',
              'PrevJump',
              'PrevPage',
              'Number',
              'NextPage',
              'NextJump',
              'FullJump',
              'Total',
            ]"
            :current-page.sync="tablePage.currentPage"
            :page-size.sync="tablePage.pageSize"
            :total="tablePage.total"
            @page-change="handlePageChange" />
        </template> -->
      </vxe-grid>
    </div>
  </div>
</template>
<script>
let FRepKey = ''
// let opername = ''
let fbillno = ''

import XEUtils from 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'
import {
  vxetableBillConfig,
  vxetableGenAdd,
  tableConfig,
  apiSql,
  apiFileSave,
  XsbList,
  getDanHao,
  beijianSave,
  beijianEdit,
  admin
} from '../../api/account'
import { checkStatus } from '../../api/salary'
import { sendsms, beijianTree, getU8 } from '../../api/peijian'
import { common } from '../../mixins/common'
import VXETablePluginShortcutKey from 'vxe-table-plugin-shortcut-key'
import '../../styles/vxetable.scss'
import HeadTable from '../salary/headTable/Billindex.vue'

VXETable.use(VXETablePluginShortcutKey, {
  // 功能键设置
  setting: {
    'table.edit.tab.rightMove': 'Enter',
    'table.edit.tab.leftMove': 'shift + Tab'
  }
})

export default {
  components: {
    HeadTable
  },
  mixins: [common],
  data() {
    return {
      formData: {},
      dialogThead: [],
      columnHeaderData: [],
      columnData: [],
      opername: '',
      aaValue: '',
      oriColumnData: [],

      configList: [],
      configModal: false,
      menusList: [],
      limits: [],
      options: [],
      lookSetShow: false,
      key: 0,
      dialogSQLModal: false,
      loadingFormSQL: false,
      formSQL: {
        gzsql: ''
      },
      rulesSQL: {},

      dialogSendMsgModal: false,
      loadingFormSendMsg: false,
      userList: [],
      sendUsrList: [],
      formSendMsg: {},
      rulesSendMsg: {},
      // mulSendMsgSelect: [],
      // pagesizes: [20, 50, 100, 300, 500],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 20
      },
      vxeDisabled: true,
      editDisabled: false,

      keyword: '',
      isHebing: '0',
      gridOptions: {
        border: true,
        showHeaderOverflow: true,
        showOverflow: true,
        showFooterOverflow: true,
        keepSource: true,
        autoResize: true,
        resizable: true,

        height: this.heightGD(),
        showFooter: true,
        round: true,
        size: 'mini',

        id: 'full_edit_1',
        rowId: 'id',
        rowConfig: {
          isHover: true,
          isCurrent: true
        },
        // columnConfig: {
        //   resizable: true
        // },

        // 自定义列配置项
        customConfig: {
          storage: true,
          checkMethod: this.checkColumnMethod
        },

        keyboardConfig: {
          isEnter: true,
          isArrow: true
        },
        editRules: {
          fzhibaoqi: [
            { required: true, message: '必须填写' }
          ] },
        // formConfig: {
        //   titleWidth: 100,
        //   titleAlign: 'right',
        //   items: [
        //     // { field: 'name', title: '名称', span: 8, titlePrefix: { message: 'app.body.valid.rName', icon: 'vxe-icon-info-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入名称' }}},
        //     // { field: 'email', title: '邮件', span: 8, titlePrefix: { useHTML: true, message: '点击链接：<a class="link" href="https://vxetable.cn" target="_blank">vxe-table官网</a>', icon: 'vxe-icon-question-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入邮件' }}},
        //     // { field: 'nickname', title: '昵称', span: 8, itemRender: { name: '$input', props: { placeholder: '请输入昵称' }}}
        //     // { field: 'role', title: '角色', span: 8, folding: true, itemRender: { name: '$input', props: { placeholder: '请输入角色' }}},
        //     // { field: 'sex', title: '性别', span: 8, folding: true, titleSuffix: { message: '注意，必填信息！', icon: 'vxe-icon-info-circle-fill' }, itemRender: { name: '$select', options: [] }},
        //     // { field: 'age', title: '年龄', span: 8, folding: true, itemRender: { name: '$input', props: { type: 'number', min: 1, max: 120, placeholder: '请输入年龄' }}}
        //     // { span: 24, align: 'center', collapseNode: true, itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: '搜索', status: 'primary' }}, { props: { type: 'reset', content: '重置' }}] }}
        //   ]
        // },

        toolbarConfig: {
          // custom: true,
          buttons: [
            // { code: 'myInsert', name: '新增', icon: 'vxe-icon-square-plus', status: 'success' },
            // { code: 'myDelete', name: '删除', icon: 'vxe-icon-delete', status: 'success' },
            // { code: 'mySave', name: '保存', icon: 'vxe-icon-save', status: 'success' }
            // { code: 'myInsertTZ', name: '新增跳转', icon: 'vxe-icon-square-plus', status: 'success' }
            // { code: 'myOper', name: '操作', icon: 'vxe-icon-square-down', status: 'success', slots: 'default', dropdowns: [{ code: 'myAA', 'name': 'AA', status: 'info', icon: 'vxe-icon-square-plus-fill' }, { code: 'myBB', 'name': 'BB', status: 'info', icon: 'vxe-icon-square-plus-fill' }] }
          ],
          slots: {
            buttons: 'toolbar_buttons'
          }
        },
        columns: [],
        data: [],

        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },

        editConfig: {
          trigger: 'click',
          mode: 'cell',
          showStatus: true, // 是否显示单元格新增与修改状态
          showIcon: false // 是否显示列头编辑图标
          // activeMethod: this.activeRowMethod
        }
      },
      fzbqList: [
        { label: '0月', value: '0月' },
        { label: '1月', value: '1月' },
        { label: '2月', value: '2月' },
        { label: '3月', value: '3月' },
        { label: '4月', value: '4月' },
        { label: '5月', value: '5月' },
        { label: '6月', value: '6月' },
        { label: '7月', value: '7月' },
        { label: '8月', value: '8月' },
        { label: '9月', value: '9月' },
        { label: '10月', value: '10月' },
        { label: '11月', value: '11月' },
        { label: '12月', value: '12月' }

      ],
      fwaibiList: [
        { label: '原币', value: '原币' },
        { label: '外币', value: '外币' }
      ]
    }
  },
  Mounted: {},
  computed: {},
  async created() {
    FRepKey = this.$route.query.key
    fbillno = this.$route.query.fbillno
    // 这里有fid -- 修改
    // opername = decodeURIComponent(this.globalDb.fname)
    this.opername = decodeURIComponent(this.globalDb.fname)

    // await this.getAdmin()

    await this.getvxetableBillConfig()
    // const $grid = this.$refs.xGrid
    // for (let i = 0; i < 100; i++) {
    //   setTimeout(() => {
    //     $grid.insertAt(-1, -1)
    //   }, 0)
    // }
    if (fbillno) {
      await this.getBeijianEdit()
      // $grid.insertAt(row, -1)
    } else {
      // await this.getvxetableGenList()
      await this.getliushuihao()
    }

    this.lookSetShow = JSON.parse(localStorage.getItem('flookSet'))

    // 菜单列表（权限）
    const menuRes = JSON.parse(localStorage.getItem('setMenuData'))
    this.menusList = menuRes

    if (menuRes.length >= 1) {
      menuRes.map((it) => {
        it.children.map((item) => {
          if (item.fobjectid === parseInt(FRepKey)) {
            this.$set(this, 'limits', item.child)
          }
        })
      })
    }

    // console.log(menuRes, this.limits, 888888)
  },
  methods: {
    activeRowMethod({ row, column, columnIndex }) {
      console.log(10000, row, column, columnIndex)
    },

    // 获取流水号
    async getliushuihao() {
      const res = await getDanHao({
        db: this.globalDb.db,
        opername: this.opername,
        FRepKey
      })
      setTimeout(() => {
        this.$set(this.formData, 'fbillno', res.Data)
        console.log(this.formData, 'this.formData getliushuihao')
      }, 0)
      // this.formData.fbillno = res.Data
    },

    editDisabledEvent({ row }) { },

    editClosedEvent({ row }) { },
    cellClosed({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
      // console.log(row, ' row cellClosed')
      // console.log(column, ' column cellClosed')
      if (row.fwaibi === '原币') {
        // 原币
        // 现在采购的采购原币单价(fcaigouybprice) = 现在买需要的采购人民币单价(fcaigourmbprice)
        // 现在的采购总价(fcaigouamount)   = 需求数量(fqtyxq) * 现在买需要的采购人民币单价(fcaigourmbprice)
        if (column.field === 'fcaigouybprice') { // 现在采购的采购原币单价
          const fcaigourmbprice = Number(row.fcaigouybprice)
          const fcaigouamount = Number(row.fqtyxq) * fcaigourmbprice
          this.gridOptions.data.map(it => {
            if (it.fid === row.fid) {
              this.$set(it, 'fcaigourmbprice', fcaigourmbprice.toFixed(2))
              this.$set(it, 'fcaigouamount', fcaigouamount.toFixed(2))
            }
          })
        }

        if (column.field === 'fcaigourmbprice') { // 现在买需要的采购人民币单价
          const fcaigouybprice = Number(row.fcaigourmbprice)
          const fcaigouamount = Number(row.fqtyxq) * Number(row.fcaigourmbprice)
          this.gridOptions.data.map(it => {
            if (it.fid === row.fid) {
              this.$set(it, 'fcaigouybprice', fcaigouybprice.toFixed(2))
              this.$set(it, 'fcaigouamount', fcaigouamount.toFixed(2))
            }
          })
        }

        if (column.field === 'fcaigouamount') { // 现在的采购总价(fcaigouamount)
          const fcaigouamount = Number(row.fcaigouamount)
          let fcaigourmbprice
          if (Number(row.fqtyxq) > 0) {
            fcaigourmbprice = fcaigouamount / Number(row.fqtyxq)
          }
          this.gridOptions.data.map(it => {
            if (it.fid === row.fid) {
              this.$set(it, 'fcaigourmbprice', fcaigourmbprice.toFixed(2))
              this.$set(it, 'fcaigouybprice', fcaigourmbprice.toFixed(2))
            }
          })
        }
      }

      // 外币
      // 现在采购的采购原币单价(fcaigouybprice) * 1.13 = 现在买需要的采购人民币单价(fcaigourmbprice)
      // 现在的采购总价(fcaigouamount)   = 需求数量(fqtyxq) * 现在买需要的采购人民币单价(fcaigourmbprice)
      if (row.fwaibi === '外币') {
        if (column.field === 'fcaigouybprice') { // 现在采购的采购原币单价
          const fcaigourmbprice = Number(row.fcaigouybprice) * 1.13
          const fcaigouamount = Number(row.fqtyxq) * fcaigourmbprice
          this.gridOptions.data.map(it => {
            if (it.fid === row.fid) {
              this.$set(it, 'fcaigourmbprice', fcaigourmbprice.toFixed(2))
              this.$set(it, 'fcaigouamount', fcaigouamount.toFixed(2))
            }
          })
        }

        if (column.field === 'fcaigourmbprice') { // 现在买需要的采购人民币单价(fcaigourmbprice)
          const fcaigouybprice = Number(row.fcaigourmbprice) / 1.13
          const fcaigouamount = Number(row.fqtyxq) * Number(row.fcaigourmbprice)
          this.gridOptions.data.map(it => {
            if (it.fid === row.fid) {
              this.$set(it, 'fcaigouybprice', fcaigouybprice.toFixed(2))
              this.$set(it, 'fcaigouamount', fcaigouamount.toFixed(2))
            }
          })
        }

        if (column.field === 'fcaigouamount') { // 现在的采购总价(fcaigouamount)
          const fcaigouamount = Number(row.fcaigouamount)
          let fcaigourmbprice
          if (Number(row.fqtyxq) > 0) {
            fcaigourmbprice = fcaigouamount / Number(row.fqtyxq)
          }
          const fcaigouybprice = fcaigourmbprice / 1.13
          this.gridOptions.data.map(it => {
            if (it.fid === row.fid) {
              this.$set(it, 'fcaigouybprice', fcaigouybprice.toFixed(2))
              this.$set(it, 'fcaigourmbprice', fcaigourmbprice.toFixed(2))
            }
          })
        }
      }
    },
    selectChangeEvent({ row, column }) {
    },
    formatField(value) {
      if (value) {
        return value
      }
    },

    // 高度
    heightGD() {
      return document.body.offsetHeight - 185 + 'px'
    },
    selectSettings(val) {
      if (val === 0) {
        this.settings()
      } else if (val === 1) {
        this.dialogSQL()
      }
    },
    settings() {
      this.configModal = true
      this.getTableConfig()
    },
    async getTableConfig() {
      try {
        this.configLoading = true
        const res = await tableConfig({
          db: this.globalDb.db,
          opername: this.opername,
          key: FRepKey,
          billtype: 1
        })
        this.configList = res.Data
        this.key = FRepKey
        this.configLoading = false
      } catch (error) {
        this.configLoading = false
      }
    },

    // SQL修改/更新
    async dialogSQL() {
      this.dialogSQLModal = true
      try {
        const res = await apiSql({
          db: this.globalDb.db,
          opername: this.opername,
          type: 1,
          FRepKey
        })

        if (res.Error === 0) {
          this.formSQL.gzsql = res.Data
          this.formSQL.FRepKey = FRepKey
        }
        setTimeout(() => {
          this.$refs['formSQL'].clearValidate()
        })
      } catch (error) {
        // console.log(error)
      }
    },

    confirmSQL() {
      this.$refs['formSQL'].validate(async(valid) => {
        if (valid) {
          try {
            this.formSQL.db = this.globalDb.db
            this.formSQL.opername = this.opername
            this.formSQL.type = 1
            const res = await apiFileSave(this.formSQL)
            if (res.Error === 0) {
              this.dialogSQLModal = false
              this.$message({
                message: res.Message,
                type: 'success'
              })
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            // console.log(error)
          }
        } else {
          return false
        }
      })
    },

    // 更新数据
    async getUpdateConfigData() {
      await this.getTableConfig()
    },

    // 添加表格背景颜色
    footerCellClassName({ $rowIndex, columnIndex }) {
      // if (columnIndex === 0) {
      if ($rowIndex === 0) {
        // return 'col-blue'
        // }
      }
    },

    // 字段
    async getvxetableBillConfig() {
      const res = await vxetableBillConfig({
        FUnControl: -1,
        opername: this.opername,
        FRepKey,
        FRepPage: 1
      })
      this.oriColumnData = res.Data
      const dataVxe = []
      // setTimeout(() => {
      if (res.Data.length > 0) {
        this.columnData.push({
          type: 'seq',
          width: 50,
          fixed: 'left'
        })
        // this.columnData.push({
        //   type: 'checkbox',
        //   width: 50,
        //   fixed: 'left'
        // })

        for (let i = 0; i < res.Data.length; i++) {
          // FRepType 202, 200 -- 文本， 131 --数值 ，135 -- 日期
          if (res.Data[i].fheaderfooter === 1) {
            // 表体字段
            if (
              res.Data[i].frepfld === 'fbeijianname' ||
              res.Data[i].frepfld === 'fbeijiancode' ||
              res.Data[i].frepfld === 'fbeijianhao'
            ) {
              this.columnData.push({
                field: res.Data[i].frepfld,
                title: res.Data[i].frepcap,

                headerAlign: 'left',
                align: 'right',

                width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                editRender: {
                  name: 'input',
                  attrs: { disabled: Boolean(res.Data[i].fisedit), placeholder: '' }
                }
              })
            } else if (res.Data[i].frepmeg === 1) {
              if (res.Data[i].frepfld === 'funit') {
                this.columnData.push({
                  field: res.Data[i].frepfld,
                  title: res.Data[i].frepcap,
                  headerAlign: 'left',
                  align: 'right',
                  width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                  editRender: { name: '$select', enabled: !res.Data[i].fisedit, options: [
                    {
                      label: '台',
                      value: '台'
                    },
                    {
                      label: '个',
                      value: '个'
                    },
                    {
                      label: '件',
                      value: '件'
                    }
                  ], placeholder: '请选择' }
                })
              }
            } else {
              const frepfld = res.Data[i].frepfld
              const isFrepfld = frepfld === 'fwaibi'// 采购币种
              if (isFrepfld) {
                // console.log(res.Data[i].frepfld, ' res.Data[i].frepfld')
                this.columnData.push({
                  field: res.Data[i].frepfld,
                  title: res.Data[i].frepcap,
                  headerAlign: 'left',
                  align: 'right',
                  width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                  slots: {
                    default: res.Data[i].frepfld + '_default',
                    edit: res.Data[i].frepfld + '_edit'
                  },
                  editRender: { name: 'option', attrs: { disabled: Boolean(res.Data[i].fisedit) }}
                })
              } else {
                this.columnData.push({
                  field: res.Data[i].frepfld,
                  title: res.Data[i].frepcap,
                  // showHeaderOverflow: true,
                  // showOverflow: true,
                  // resizable: true,
                  width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                  editRender: { name: 'input', attrs: { disabled: Boolean(res.Data[i].fisedit), placeholder: '' }}
                })
              }
            }
          } else {
            // 表头
            this.dialogThead.push(res.Data[i])
            // columnHeaderData
            this.columnHeaderData.push({
              field: res.Data[i].frepfld,
              title: res.Data[i].frepcap,
              // showHeaderOverflow: true,
              // showOverflow: true,
              // resizable: true,
              titleColon: true,
              titleWidth: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0
            })

            // this.$set(this.formData, i, data[i])
            // this.formData.items = this.columnHeaderData
          }
        }
        // console.log(this.dialogThead, this.columnHeaderData)+
        //    for (const i in data) {
        //   this.$set(this.form, i, data[i])
        // }

        this.dialogThead.map((item) => {
          dataVxe[item.frepfld] = ''
        })
        for (const i in dataVxe) {
          this.$set(this.formData, i, dataVxe[i])
        }

        this.gridOptions.columns = this.columnData
      }
      // }, 1000)
    },

    // formatFstatus(row) {
    //   console.log(row, 88888888888)

    //   }
    // },

    async vxeU8() {
      const res = await getU8({
        opername: decodeURIComponent(this.globalDb.fname),
        fbillno: this.formData.fbillno,
        FRepKey
      })
      if (res.Error === 0) {
        this.$message({
          message: '同步成功',
          type: 'success'
        })
        this.gridOptions.data = res.Data
        const $grid = this.$refs.xGrid
        for (let i = 0; i < 10; i++) {
          setTimeout(() => {
            $grid.insertAt(-1, -1)
          }, 0)
        }
      } else {
        this.$message({
          message: '失败',
          type: 'error'
        })
      }
    },

    //
    async vxeSendSms() {
      this.dialogSendMsgModal = true
      await this.getBeijianTree()
    },
    handleNodeClick(data) {
      console.log(data)
    },
    async confirmSendMsg() {
      const selectMsgArr = this.$refs.selectTree.getCheckedKeys(true)
      this.dialogSendMsgModal = true
      try {
        const fcontent = this.formSendMsg.fcontent
        const fbillno = this.formData.fbillno
        if (selectMsgArr.length) {
          const fid = selectMsgArr.join(',')
          if (!fid) {
            this.$message({
              message: '手机号为空',
              type: 'error'
            })
            return
          }

          const res = await sendsms({
            opername: decodeURIComponent(this.globalDb.fname),
            fid,
            fcontent,
            fbillno
          })
          console.log(res, ' res')
          if (res.Error === 0) {
            this.mulSendMsgSelect = []
            this.formSendMsg.fcontent = ''
            this.dialogSendMsgModal = false
          }
        } else {
          this.$message({
            message: '未选中发送信息通知人员',
            type: 'error'
          })
          return
        }
      } catch (error) {
        this.dialogSendMsgModal = false
      }
    },
    async getBeijianTree() {
      try {
        this.sendMsgLoading = true
        const res = await beijianTree({
          opername: decodeURIComponent(this.globalDb.fname)
        })
        console.log(res, ' res')

        this.sendUsrList = res.Data
        this.sendMsgLoading = false
      } catch (error) {
        this.sendMsgLoading = false
        console.log(error)
      }
    },
    async getAdmin() {
      try {
        this.sendMsgLoading = true
        const res = await admin({
          db: this.globalDb.db,
          opername: this.loginname,
          keyword: this.keyword,
          username: this.loginname,
          limit: this.pagesize,
          page: this.currentPage
        })
        this.userList = res.result
      } catch (error) {
        console.log(error)
      }
    },
    // 刷新
    refresh() {
      window.location.reload()
    },

    // 新增
    vxeAdd(row) {
      console.log(row, 'row')
      const $grid = this.$refs.xGrid
      $grid.insertAt(row, -1)
      // const total = 50
      // for (var i = 0; i <= total; i++) {
      //   $grid.insert({})
      // }
    },
    goBack() {
      this.$router.push('/peijian/pjcg')
    },
    // 保存
    async vxeSave() {
      const $grid = this.$refs.xGrid
      const {
        insertRecords,
        removeRecords,
        updateRecords
      } = $grid.getRecordset()
      const { tableData } = $grid.getTableData()
      console.log(
        insertRecords,
        removeRecords,
        updateRecords,
        111111,
        this.formData,
      )
      if (
        insertRecords.length === 0 &&
        updateRecords.length === 0 &&
        removeRecords.length === 0
      ) {
        VXETable.modal.message({
          content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`,
          status: 'warning'
        })
        return
      }
      // 修改时 是否已审核
      if (updateRecords.length > 0) {
        console.log(updateRecords, ' updateRecords')
        const isFstatus = updateRecords.filter((it) => Number(it.fstatus2) === 1)
        if (isFstatus.length) {
          this.$message({
            message: '已审核，不能修改！',
            type: 'error'
          })
          return
        }
      }

      const insertRecordsArr = []
      insertRecords.map(it => {
        if (it.fbeijianname && it.fbeijiancode && it.fbeijianhao) {
          insertRecordsArr.push(it)
        }
      })

      const tableDataArr = []
      tableData.map(it => {
        if (it.fbeijianname && it.fbeijiancode && it.fbeijianhao) {
          tableDataArr.push(it)
        }
      })

      // console.log(insertRecords, removeRecords, updateRecords, insertRecords.length > 0, updateRecords.length > 0, removeRecords.length > 0)
      try {
        const res = await beijianSave({
          FRepKey,
          opername: this.opername,
          insertRecords: insertRecordsArr,
          updateRecords,
          removeRecords,
          tableData: tableDataArr,
          formdata: this.formData
        })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
        } else {
          this.$message({
            message: res.Message,
            type: 'error'
          })
        }
        // this.getvxetableGenList()
      } catch (error) {
        console.log(error)
      }

      // VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'success' })
    },
    editActivedEvent({
      row,
      rowIndex,
      $rowIndex,
      column,
      columnIndex,
      $columnIndex
    }) {
      this.editDisabled = columnIndex > 2
    },
    // 删除
    async vxeDel() {
      console.log(11111)
      const $grid = this.$refs.xGrid

      // 删除当前行    VXETable.modal.alert($grid.getCurrentRecord())
      $grid.remove($grid.getCurrentRecord())

      // if ($grid.getCheckboxRecords().length === 0) {
      //   VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
      //   return
      // }

      // 判断已审核
      // const dataTemp = $grid.getCheckboxRecords()
      // const isFstatus = dataTemp.filter(it => Number(it.fstatus) === 1)
      // if (isFstatus.length) {
      //   this.$message({
      //     message: '已审核，不能删除！',
      //     type: 'error'
      //   })
      //   return
      // }

      // const { removeRecords } = $grid.getRecordset()

      // const res = await vxetableGenAdd({ FRepKey, opername: this.opername, removeRecords })
      // if (res.Error === 0) {
      //   VXETable.modal.message({ content: ` 删除 ${removeRecords.length} 条`, status: 'success' })
      //   this.getvxetableGenList()
      // }
    },

    // 1—审核，0—反审
    async check(Fstatus) {
      const $grid = this.$refs.xGrid
      if ($grid.getCheckboxRecords().length === 0) {
        VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
        return
      }
      const checkData = []
      $grid.getCheckboxRecords().map((it) => {
        checkData.push(it.fid)
      })

      if (Number(Fstatus) === 1) {
        this.$confirm('是否审核, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning'
        })
          .then(async() => {
            try {
              const res = await checkStatus({
                db: this.globalDb.db,
                opername: decodeURIComponent(this.globalDb.fname),
                loginname: decodeURIComponent(this.globalDb.fname),
                FRepKey,
                Fstatus, // 1—审核，0—反审
                fid: checkData.join(',')
              })
              if (res.Error === 0) {
                this.$message({
                  message: res.Message,
                  type: 'success'
                })
                await this.getvxetableGenList()
              } else {
                this.loadingForm = false
                this.$message({
                  message: res.Message,
                  type: 'error'
                })
              }
            } catch (error) {
              console.log(error)
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      } else {
        try {
          const res = await checkStatus({
            db: this.globalDb.db,
            opername: decodeURIComponent(this.globalDb.fname),
            loginname: decodeURIComponent(this.globalDb.fname),
            FRepKey,
            Fstatus, // 1—审核，0—反审
            fid: checkData.join(','),
            appname: ''
          })
          if (res.Error === 0) {
            this.$message({
              message: res.Message,
              type: 'success'
            })
            await this.getvxetableGenList()
          } else {
            this.loadingForm = false
            this.$message({
              message: res.Message,
              type: 'error'
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
    },

    // 内容列表
    async getvxetableGenList() {
      const param = {
        opername: decodeURIComponent(this.globalDb.fname),
        FRepKey,
        keyword: this.keyword,
        isHebing: this.isHebing,
        fstatus: this.fstatus,
        page: this.tablePage.currentPage,
        pageSize: this.tablePage.pageSize
      }
      const res = await XsbList(param)
      setTimeout(() => {
        this.tablePage.total = res.total
        this.gridOptions.data = res.Data
        // res.Data
      }, 0)
    },
    // 编辑内容设置
    async getBeijianEdit() {
      const param = { FRepKey, fbillno, db: this.globalDb.db }
      const res = await beijianEdit(param)
      setTimeout(() => {
        if (res.Data && res.Data.length) {
          this.gridOptions.data = res.Data
          this.$set(this.formData, 'fbillno', res.Data[0].fbillno)
          this.$set(this.formData, 'fchuanmin', res.Data[0].fchuanmin)
          this.$set(this.formData, 'fchuanhao', res.Data[0].fchuanhao)
          this.$set(this.formData, 'fmodel', res.Data[0].fmodel)
          this.$set(this.formData, 'fprodectno', res.Data[0].fprodectno)
          this.$set(this.formData, 'fcustomer', res.Data[0].fcustomer)
          this.$set(this.formData, 'fzhibaoqi', res.Data[0].fzhibaoqi)
        }
      }, 0)
    },
    // 分页
    handlePageChange({ currentPage, pageSize }) {
      console.log(22222, currentPage, pageSize)
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.getvxetableGenList()
    },

    addressClickEvent(row) {
      VXETable.modal.alert(`address点击事件：${row.address}`)
    },

    // 按钮点击
    async toolbarButtonClickEvent({ code }) {
      console.log(code, 'code toolbarButtonClickEvent')
      const $grid = this.$refs.xGrid
      switch (code) {
        case 'myInsert':
          console.log(234, $grid)
          $grid.insert({})
          break
        // 保存
        case 'mySave':
          setTimeout(async() => {
            const {
              insertRecords,
              removeRecords,
              updateRecords
            } = $grid.getRecordset()

            if (
              insertRecords.length === 0 &&
              updateRecords.length === 0 &&
              removeRecords.length === 0
            ) {
              VXETable.modal.message({
                content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`,
                status: 'warning'
              })
              return
            }
            console.log(
              insertRecords,
              removeRecords,
              updateRecords,
              insertRecords.length > 0,
              updateRecords.length > 0,
              removeRecords.length > 0,
            )
            try {
              const res = await vxetableGenAdd({
                FRepKey,
                opername: this.opername,
                insertRecords,
                updateRecords,
                removeRecords
              })
              if (res.Error === 200) {
                this.getvxetableGenList()
                VXETable.modal.message({
                  content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`,
                  status: 'success'
                })
              } else {
                VXETable.modal.message({
                  content: res.Message,
                  status: 'error'
                })
              }
            } catch (error) {
              console.log(error)
            }
          })
          break
        // 删除
        case 'myDelete':
          if ($grid.getCheckboxRecords().length === 0) {
            VXETable.modal.message({
              content: `请选中一行`,
              status: 'warning'
            })
            return
          }
          setTimeout(async() => {
            const { removeRecords } = $grid.getRecordset()

            $grid.removeCheckboxRow()
            const res = await vxetableGenAdd({
              FRepKey,
              opername: this.opername,
              removeRecords
            })
            if (res.Error === 0) {
              VXETable.modal.message({
                content: ` 删除 ${removeRecords.length} 条`,
                status: 'success'
              })
              this.getvxetableGenList()
            }

            // $grid.clearSelected()
            // $grid.clearCheckboxRow()
          })
          break

        case 'myInsertTZ':
          break

        case 'myAA':
          VXETable.modal.message({ content: '新增', status: 'success' })
          break
      }
    },

    sumNum(list, field) { // DONE
      let count = 0
      list.forEach(item => {
        count += Number(item[field]) * 100
      })
      return (count / 100)
    },

    formatAmount({ cellValue }) {
      return cellValue
        ? `￥${XEUtils.commafy(XEUtils.toNumber(cellValue), { digits: 2 })}`
        : ''
    },
    formatDate({ cellValue }) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:ss:mm')
    },
    checkColumnMethod({ column }) {
      if (['nickname', 'role'].includes(column.property)) {
        return false
      }
      return true
    }
  }
}
</script>
